package com.jk.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jk.dao.InhabitantDao;
import com.jk.pojo.CountBean;
import com.jk.pojo.InhabitantBean;
import com.jk.utils.ReturnMsgUtils;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.IdsQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * @ClassName InhabitantService
 * @Descripttion TODO
 * @Author DELL
 * @Date 2022/10/16 19:30
 * @Version 0.001
 */
@Service
public class InhabitantService {

    @Autowired
    private InhabitantDao inhabitantDao;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private RestHighLevelClient client;

    /**
     * @Author: binzi
     * @Description:查询居民表
     * @Date: 2022/10/16 19:42
     * @Return:
     **/
    public Map findInhabitant(InhabitantBean bean) {
        //索引名称
        String index = "inhabitant";
        GetIndexRequest indexRequest = new GetIndexRequest(index);
        boolean exists = false;
        //判断es中索引是否存在 存在true,不存在false
        try {//true
            exists = client.indices().exists(indexRequest, RequestOptions.DEFAULT);
            if (exists == false){//false
                QueryWrapper<InhabitantBean> queryWrapper = new QueryWrapper<>();
                List<InhabitantBean> inhabitantBeans = inhabitantDao.selectList(queryWrapper);
                inhabitantBeans.forEach(InhabitantBean->{
                    elasticsearchRestTemplate.save(InhabitantBean);
                });
                return ReturnMsgUtils.returnMsg(200,"MySql中的数据",inhabitantBeans);
            }else {//true
                //先new 一个List 之后查出来的数据
                List<InhabitantBean> list = new ArrayList<>();

                //查询条件
                BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

                //姓名模糊查
                if (bean.getName() != null && bean.getName() != ""){
                    boolQueryBuilder.must(QueryBuilders.matchQuery("name",bean.getName()));
                }

                //签约状态精确查
                if (bean.getState() != null){
                    boolQueryBuilder.must(QueryBuilders.termQuery("state",bean.getState()));
                }

                //服务包精确查
                if (bean.getService() != null){
                    boolQueryBuilder.must(QueryBuilders.termQuery("service",bean.getService()));
                }

                //签约机构精确查
                if (bean.getMechanism() != null){
                    boolQueryBuilder.must(QueryBuilders.termQuery("mechanism",bean.getMechanism()));
                }
                //高亮
                HighlightBuilder highlightBuilder = new HighlightBuilder();
                //实体类要高亮的value字段
                highlightBuilder.field("name");
                highlightBuilder.preTags("<font color='red'>");
                highlightBuilder.postTags("</font>");

                NativeSearchQuery query = new NativeSearchQueryBuilder()
                        .withQuery(boolQueryBuilder)
                        .withHighlightBuilder(highlightBuilder)
                        .build();
                SearchHits<InhabitantBean> search = elasticsearchRestTemplate.search(query, InhabitantBean.class);

                //获取查询的 hit
                List<SearchHit<InhabitantBean>> searchHits = search.getSearchHits();

                //循环获取到的hit
                searchHits.forEach(hit->{
                    //获取高亮的内容
                    Map<String, List<String>> highlightFields = hit.getHighlightFields();
                    //判断高亮的字段是否有值
                    hit.getContent().setName(highlightFields.get("name") == null ? hit.getContent().getName():highlightFields.get("name").get(0));
                    list.add(hit.getContent());
                });

                return ReturnMsgUtils.returnMsg(200,"Es中的数据",list);
            }
        } catch (IOException e) {//false
            e.printStackTrace();
            return ReturnMsgUtils.returnMsg(500,"服务器异常",null);
        }
    }

    /**
     * @Author: binzi
     * @Description:根据Id查下居民表的数据
     * @Date: 2022/10/17 9:37
     * @Return: com.jk.pojo.InhabitantBean
     **/
    public InhabitantBean findInhabitantById(Integer id) {
        //索引名称
        String index = "inhabitant";
        GetIndexRequest indexRequest = new GetIndexRequest(index);
        boolean exists = false;
        //判断es中索引是否存在 存在true,不存在false
        try {//true
            exists = client.indices().exists(indexRequest, RequestOptions.DEFAULT);
            if (exists == false){//false
               return inhabitantDao.selectById(id);
            }else {//true
                IdsQueryBuilder ids = QueryBuilders.idsQuery();
                ids.addIds(id.toString());
                NativeSearchQuery build = new NativeSearchQueryBuilder()
                        .withQuery(ids)
                        .build();
                SearchHit<InhabitantBean> inhabitantBeanSearchHit = elasticsearchRestTemplate.searchOne(build, InhabitantBean.class);
                if (inhabitantBeanSearchHit != null){
                    InhabitantBean content = inhabitantBeanSearchHit.getContent();
                    return content;
                }else {
                    return null;
                }
            }
        } catch (IOException e) {//false
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @Author: binzi
     * @Description:查询当前时间的前七点数据
     * @Date: 2022/10/17 19:57
     * @Return: java.util.Map
     **/
    public Map findInhabitantByWeek() {
        List<Integer>  list =  inhabitantDao.findInhabitantByWeek();
        return ReturnMsgUtils.returnMsg(200,"查询当前时间的前七点数据",list);
    }

    /**
     * @Author: binzi
     * @Description:查询各种病的总数
     * @Date: 2022/10/18 9:44
     * @Return: java.util.Map
     **/
    public Map findInhabitantByResidentLabelCount() {
        List<Integer> list = inhabitantDao.findInhabitantByResidentLabelCount();
        return ReturnMsgUtils.returnMsg(200,"查询各种病的总数",list);
    }

    /**
     * @Author: binzi
     * @Description:居民总数量
     * @Date: 2022/10/18 10:01
     * @Return: java.util.Map
     **/
    public Integer findByCountId() {
        return inhabitantDao.findByCountId();
    }

    /**
     * @Author: binzi
     * @Description:签约居民数量
     * @Date: 2022/10/18 10:10
     * @Return: java.util.Map
     **/
    public Integer findByStatusCount() {
        return inhabitantDao.findByStatusCount();
    }

    /**
     * @Author: binzi
     * @Description:统计三个团队本周已签约的数据
     * @Date: 2022/10/18 15:29
     * @Return: java.util.Map
     **/
    public Map findInhabitantByDateCount() {
        List<CountBean> list = new ArrayList<CountBean>();

        CountBean countBean = new CountBean();
        List<Integer> list1 =  inhabitantDao.findInhabitantByDateCount();
        countBean.setName("王皓团队");
        countBean.setCount1(list1.get(0));
        countBean.setCount2(list1.get(1));
        countBean.setCount3(list1.get(2));
        countBean.setCount4(list1.get(3));
        countBean.setCount5(list1.get(4));
        countBean.setCount6(list1.get(5));
        countBean.setCount7(list1.get(6));

        CountBean count2Bean = new CountBean();

        List<Integer> list2 =  inhabitantDao.findInhabitantByDateCount2();
        count2Bean.setName("胡曼团队");
        count2Bean.setCount1(list2.get(0));
        count2Bean.setCount2(list2.get(1));
        count2Bean.setCount3(list2.get(2));
        count2Bean.setCount4(list2.get(3));
        count2Bean.setCount5(list2.get(4));
        count2Bean.setCount6(list2.get(5));
        count2Bean.setCount7(list2.get(6));

        CountBean count3Bean = new CountBean();
        List<Integer> list3 =  inhabitantDao.findInhabitantByDateCount3();
        count3Bean.setName("李维团队");
        count3Bean.setCount1(list3.get(0));
        count3Bean.setCount2(list3.get(1));
        count3Bean.setCount3(list3.get(2));
        count3Bean.setCount4(list3.get(3));
        count3Bean.setCount5(list3.get(4));
        count3Bean.setCount6(list3.get(5));
        count3Bean.setCount7(list3.get(6));
        list.add(countBean);
        list.add(count2Bean);
        list.add(count3Bean);

        return ReturnMsgUtils.returnMsg(200,"11",list);
    }
}
